<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="900"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog(false)"
  >
    <el-form ref="addOrEditFormRef" v-loading="loading" :model="formData" :rules="rules" label-width="170" size="">
      <!-- 添加保证金账户 -->
      <el-row justify="start" class="d_left">
        <el-col :span="12" class="">
          <el-form-item label="项目名称" prop="projectId">
            <el-input v-model="selectedAccount.projectName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: -15px" @click="handleSelectAccount"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体名称" prop="paymentName">
            <el-input v-model="selectedAccount.paymentName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="缴纳主体统一社会信用代码" prop="paymentCode">
            <el-input v-model="selectedAccount.paymentCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="账户编号" prop="guaranteeAccountCode">
            <el-input v-model="selectedAccount.guaranteeAccountCode" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="账户方式" prop="guaranteeAccountTypeName">
            <el-input v-model="selectedAccount.guaranteeAccountTypeName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="动用通知书文号" prop="notificationLetter">
            <el-input v-model="formData.notificationLetter" placeholder="请输入动用通知文书号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="支出编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入支出编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="保险(函)单号" prop="guaranteeLetterNo">
            <el-input v-model="formData.guaranteeLetterNo" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="">
          <el-form-item label="支出金额" prop="amount">
            <!-- <el-input v-model="formData.amount" type="number" placeholder="请输入支出金额" /> -->
            <money-input v-model="formData.amount" unit="元"></money-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="">
          <el-form-item label="支付日期" prop="payDate">
            <el-date-picker
              v-model="formData.payDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传支出明细表" prop="attachments">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :action="actionUrl"
              :method="'post'"
              :show-file-list="false"
              :limit="1"
              :headers="headers"
              accept=".xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="handleBeforeUpload"
            >
              <el-button plain size="small">上传文件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传xls,xlsx且不大于5M的文件</div>
                <el-link v-loading="loadingTemplate" type="primary" @click="handleDownloadTemplate">下载模板</el-link>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col>
          <el-table v-loading="loadTableing" :data="tableList" highlight-current-row border>
            <el-table-column label="务工人员公民身份号码" prop="cardNo" align="center" min-width="110" />
            <el-table-column label="务工人员姓名" prop="userName" align="center" min-width="110" />
            <el-table-column label="工资支付金额" prop="amount" align="center" min-width="110" />
            <el-table-column label="工资支付方式" prop="payType" align="center" min-width="110" />
            <el-table-column fixed="right" label="操作" align="center" width="80">
              <template #default="scope">
                <el-button type="primary" link @click="handelDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <select-guarantee-account :dialog-select="dialogAccount" @select-send-close="sendClose"></select-guarantee-account>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import MoneyInput from "@/components/MoneyInput/index.vue";
import { ProjectGuaranteeExpenditureEditForm } from "@/api/guarantee/types";
import SelectGuaranteeAccount from "@/views/common/SelectProjectGuaranteeAccount/index.vue";
import type { UploadUserFile } from "element-plus";
import { downloadFile } from "@/utils";
import { useUserStore } from "@/store/modules/user";

import {
  CreateProjectGuaranteeExpenditure,
  GetProjectGuaranteeExpenditure,
  DownloadProjectGuaranteeExpenditureTemplate,
} from "@/api/guarantee/index";
import { FormRules } from "element-plus";
//上传地址
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/sysuser/guarantee/expenditure/import`);
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "创建保证金账户",
      footBtn: "核实账户信息",
      id: 0,
      type: 1,
    }),
  },
});
const uploadRef = ref();
const useUser = useUserStore();
let headers = ref({
  Authorization: useUser.token,
});

const { dialogAddOrEdit } = toRefs(props);

const dialogAccount = ref({
  visible: false,
});

const emit = defineEmits(["sendClose"]);

const loading = ref(false);
const loadingTemplate = ref(false);
const formData = reactive<ProjectGuaranteeExpenditureEditForm>({});
const addOrEditFormRef = ref(ElForm);
const selectedAccount = ref<any>({});
const tableList = ref<any[]>([]);
const loadTableing = ref(false);

const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (tableList.value.length == 0) {
    callback(new Error("请上传支出明细!"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<ProjectGuaranteeExpenditureEditForm>>({
  //添加保证金
  projectId: [{ required: true, message: "请选择项目", trigger: "blur" }],
  notificationLetter: [{ required: true, message: "请输入通知书文号", trigger: "blur" }],
  code: [{ required: true, message: "请输入收入编号", trigger: "blur" }],
  amount: [{ required: true, message: "请输入收入金额", trigger: "blur" }],
  payDate: [{ required: true, message: "请选择收入日期", trigger: "blur" }],
  guaranteeLetterNo: [],
  attachments: [
    {
      required: true,
      message: "请上传支出明细",
      trigger: "change",
      validator: validatorAttachment,
    },
  ],
});

const handleSelectAccount = function () {
  dialogAccount.value.visible = true;
};

const sendClose = function (info: any) {
  dialogAccount.value.visible = false;
  if (info) {
    selectedAccount.value = info;
    formData.guaranteePaymentId = info.id;
    formData.projectId = info.projectId;
    if (info.guaranteeAccountType != 1) {
      rules.guaranteeLetterNo = [{ required: true, message: "请输入保险单号", trigger: "blur" }];
    } else {
      rules.guaranteeLetterNo = [];
    }
  }
};

/* 附件上传 */

const handleBeforeUpload = () => {
  loadTableing.value = true;
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传1个附件");
};
//上传成功
const handleUploadSuccess = (response: any) => {
  loadTableing.value = false;
  uploadRef.value.clearFiles();
  if (response.type === 0) {
    if (response.success) {
      tableList.value = response.data;
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};
//处理上传失败
const handleUploadError = (err: any) => {
  loadTableing.value = false;
  ElMessage.error(err);
};

const handelDelete = (row: any) => {
  tableList.value.splice(tableList.value.indexOf(row), 1);
};
//下载导入模板
const handleDownloadTemplate = () => {
  loadingTemplate.value = true;
  DownloadProjectGuaranteeExpenditureTemplate()
    .then((res) => {
      downloadFile(res);
    })
    .finally(() => {
      loadingTemplate.value = false;
    });
};

//初始化表单
const initForm = () => {
  if (dialogAddOrEdit.value.id) {
    loading.value = true;

    GetProjectGuaranteeExpenditure(dialogAddOrEdit.value.id)
      .then((res) => {
        if (res.success) {
          Object.assign(formData, res.data);
        } else {
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

onMounted(() => {
  //上传文件
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(query: boolean, data?: any) {
  resetForm();
  emit("sendClose", query, data);
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.id = undefined;
  fileList.value = [];
  tableList.value = [];
  selectedAccount.value = {};
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      formData.details = tableList.value;
      CreateProjectGuaranteeExpenditure(formData)
        .then((res) => {
          if (res.success) {
            closeDialog(true);
          } else {
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
.d_left {
  margin-left: 10px;
}
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 80%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
